package com.xxxx.server.config;



import com.xxxx.server.service.IMailLogService;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class RabbitConfig {
    public static final String MAIL_QUEUE_NAME = "mail_queue";
    public static final String MAIL_EXCHANGE_NAME = "mail_exchange";
    public static final String MAIL_ROUTING_KEY_NAME = "mail_routing_key";

    @Autowired
    private CachingConnectionFactory cachingConnectionFactory;
    @Autowired
    private IMailLogService mailLogService;


    @Bean
    public RabbitTemplate rabbitTemplate(){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);

        //消息是否成功发送到交换机
        rabbitTemplate.setConfirmCallback(((correlationData, ack, cause) -> {
            if(ack){
                //获取消息id
                String msgId = correlationData.getId();
                //更新数据为消息投递中
                mailLogService.updateStatusByMsgId(msgId,0);
            }
        }));

        return rabbitTemplate;
    }

    @Bean
    public Queue mailQueue() {
        return new Queue(MAIL_QUEUE_NAME, true);
    }

    @Bean
    public DirectExchange mailExchange() {
        return new DirectExchange(MAIL_EXCHANGE_NAME, true, false);
    }

    @Bean
    public Binding mailBinding() {
        return BindingBuilder.bind(mailQueue()).to(mailExchange()).with(MAIL_ROUTING_KEY_NAME);
    }

}
